import React, { useState, useImperativeHandle } from 'react';
import { Form, Input, Modal, message, TreeSelect, Select } from 'antd';
import { create } from '../api';

/**
 * 系统管理/权限管理/菜单管理/新增弹窗
 */
const AddForm = ({ menus, getAll }: MenuAPI.Props, ref: any) => {
  const [form] = Form.useForm();
  const { SHOW_PARENT } = TreeSelect;
  const [visible, setVis] = useState(false);
  useImperativeHandle(ref, () => ({ setVis }));
  const rules = [{ required: true, message: '不能为空' }];

  const onCancel = () => {
    setVis(false);
  };

  const onFinish = () => {
    form.validateFields().then(async (values) => {
      const res = await create(values);
      if (res.code === 200) {
        getAll();
        message.success(res.msg);
      } else {
        message.error(res.msg);
      }
      form.resetFields();
      onCancel();
    });
  };

  return (
    <Modal
      title="新增菜单"
      width={600}
      open={visible}
      onOk={onFinish}
      onCancel={onCancel}
      afterClose={() => form.resetFields()}
    >
      <Form name="addPermission" autoComplete="off" form={form}>
        <Form.Item
          label="名称"
          name="name"
          rules={[
            { required: true, message: '' },
            () => ({
              validator(_, value) {
                if (value.trim() !== '') {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('请输入名称!'));
              },
            }),
          ]}
        >
          <Input placeholder="请输入名称" />
        </Form.Item>

        <Form.Item label="类型" name="type" rules={rules}>
          <Select
            placeholder="请选择类型"
            options={[
              { value: 1, label: '菜单' },
              { value: 2, label: '按钮' },
            ]}
          />
        </Form.Item>

        <Form.Item label="路径名称" name="path" rules={rules}>
          <Input placeholder="请输入路径名称，如/admin" />
        </Form.Item>

        <Form.Item label="上级菜单" name="pid" rules={rules}>
          <TreeSelect
            treeData={menus}
            placeholder="请选择上级菜单"
            showCheckedStrategy={SHOW_PARENT}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default React.forwardRef(AddForm);
